package main

import (
	"context"
	"fmt"
	grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
	grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
	grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
	"go-grpc-retry/proto"
	"google.golang.org/grpc"
	"net"
	"time"
)

type HelloServer struct {
}

func (s *HelloServer) Hello(context context.Context, request *proto.HelloRequest) (*proto.HelloResponse, error) {
	fmt.Println(request.Name)
	time.Sleep(2 * time.Second)
	return &proto.HelloResponse{
		Reply: "收到客户端的数据：" + request.Name,
	}, nil
}

func main() {
	// 使用第三方拦截器，使用了grpc_auth和grpc_recovery
	myAuthFunction := func(ctx context.Context) (context.Context, error) {
		fmt.Println("走了认证")
		return ctx, nil
	}

	opt := grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
		grpc_auth.UnaryServerInterceptor(myAuthFunction),
		grpc_recovery.UnaryServerInterceptor(),
	))

	g := grpc.NewServer(opt)
	// 使用拦截器结束
	s := HelloServer{}
	proto.RegisterHelloServer(g, &s)
	lis, err := net.Listen("tcp", "0.0.0.0:50052")
	if err != nil {
		panic("启动服务异常")
	}
	_ = g.Serve(lis)
}
